package com.ruoyi.system.service.impl;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.ruoyi.common.utils.DateUtil;
import com.ruoyi.system.domain.StudyReport;
import com.ruoyi.system.domain.StudyReport.TestRecord;
import com.ruoyi.system.domain.StudyReport.Tests;
import com.ruoyi.system.domain.StudyReport.WeeklyProgress;
import com.ruoyi.system.domain.StudyReport.WordLearning;
import com.ruoyi.system.mapper.SysWordLearningProgressMapper;
import com.ruoyi.system.service.IStudyReportService;

@Service
public class StudyReportServiceImpl implements IStudyReportService {
    @Autowired
    private SysWordLearningProgressMapper sysWordLearningProgressMapper;

    @Override
    public StudyReport getStudyReport(Long studentId, Integer pageSize, Integer pageIndex) {
        StudyReport report = new StudyReport();

        // 设置单词学习记录
        WordLearning wordLearning = new WordLearning();
        List<WeeklyProgress> weeklyProgressList = new ArrayList<>();

        // 生成最近7天的学习记录
        Calendar calendar = Calendar.getInstance();
        for (int i = 6; i >= 0; i--) {
            calendar.add(Calendar.DAY_OF_MONTH, -i);
            WeeklyProgress progress = new WeeklyProgress();
            String date = DateUtil.getYYYY_MM_DD(calendar.getTime()); // 日期
            progress.setDate(date);
            Integer learningWords = sysWordLearningProgressMapper.sumStudyed(studentId, null, null, date, date);
            progress.setLearningWords(learningWords); // 随机生成30-60个单词
            weeklyProgressList.add(progress);
            calendar.add(Calendar.DAY_OF_MONTH, i);
        }
        wordLearning.setWeeklyProgress(weeklyProgressList);
        report.setWordLearning(wordLearning);

        // 设置测试记录
        Tests tests = new Tests();
        List<TestRecord> testRecords = new ArrayList<>();

        // 计算分页参数
        int defaultPageSize = 10;
        int size = pageSize != null ? pageSize : defaultPageSize;
        int index = pageIndex != null ? pageIndex : 1;

        // 从持久化存储中获取测试记录
        synchronized (this) {
            if (persistentTestRecords == null) {
                persistentTestRecords = new ArrayList<>();
            }
            
            int total = persistentTestRecords.size();
            int start = (index - 1) * size;
            int end = Math.min(start + size, total);

            if (start < total) {
                testRecords = persistentTestRecords.subList(start, end);
            }

            tests.setTotal(total);
            tests.setTestRecords(testRecords);
            report.setTests(tests);
        }

        return report;
    }

    // 用于存储测试记录的静态列表
    private static List<TestRecord> persistentTestRecords = new ArrayList<>();
}